package com.agv.web.security;

import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;
import org.json.JSONArray;
import org.json.JSONML;
import org.json.JSONObject;
import org.json.JSONString;

import com.agv.core.exception.SecurityException;
import com.agv.core.objectDomain.Modulo;
import com.agv.core.objectDomain.Usuario;
import com.agv.core.services.ISecurityService;

/**
 * MyEclipse Struts Creation date: 05-31-2011
 * 
 * XDoclet definition:
 * 
 * @struts.action path="/agvWebLogin" name="loginForm" input="/pages/login.jsp"
 *                scope="request" validate="true"
 */
public class LoginAction extends DispatchAction {

	private ISecurityService securityService;

	/**
	 * Method execute
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		LoginForm loginForm = (LoginForm) form;
		try {
			String cdUser = request.getParameter("username");
			String pwPassword = request.getParameter("password");

			Usuario usuario = securityService.login(cdUser, pwPassword);

			if (usuario.isCdPrimerAcceso()) {
				request.getSession().setAttribute("primerAcceso", "si");
				request.getSession().setAttribute("usuarioObj", usuario);
				request.getSession().setAttribute("perfilObj",
						usuario.getPerfil());
				return mapping.findForward("login");
			}

			request.getSession().removeAttribute("catCompleto");
			request.getSession().removeAttribute("catInsertado");
			request.getSession().removeAttribute("catalogoObj");
			request.getSession().removeAttribute("altaCatalogo");
			request.getSession().removeAttribute("pasoActual");
			request.getSession().removeAttribute("totalPasos");
			request.getSession().removeAttribute("buscaCatalogo");
			request.getSession().removeAttribute("actualizarCatalogo");
			request.getSession().removeAttribute("modulo");
			request.getSession().removeAttribute("subModulo");
			request.getSession().removeAttribute("funcion");

			request.getSession().setAttribute("ruta", "");
			request.getSession().setAttribute("usuarioObj", usuario);
			request.getSession().setAttribute("perfilObj", usuario.getPerfil());
		} catch (SecurityException e) {
			ActionMessages messages = new ActionMessages();
			ActionMessage msg = new ActionMessage("agv.adm.sec.incorrecto");
			messages.add("message", msg);
			saveMessages(request, messages);
			return mapping.findForward("login");
		}
		return mapping.findForward("inicio");
	}

	public ActionForward getFunctions(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			Usuario usuario = (Usuario) request.getSession().getAttribute(
					"usuarioObj");

			ServletOutputStream out = response.getOutputStream();

			List<Modulo> modulos = usuario.getModulos();
			JSONArray array = new JSONArray();

			JSONObject object = new JSONObject();

			for (Modulo module : modulos) {
				JSONArray arrayGuardaModulo = new JSONArray();
				JSONArray arrayGuardaSubModulo = new JSONArray();

				for (int i = 0; i < module.getSubModulos().size(); i++) {
					JSONObject subModules = new JSONObject();
					subModules.put("text", module.getSubModulos().get(i)
							.getNbSubModulo().trim());
					subModules.put("iconCls", module.getSubModulos().get(i)
							.getNbIcon());

					JSONArray arrayGuardaFunciones = new JSONArray();
					for (int j = 0; j < module.getSubModulos().get(i)
							.getFunciones().size(); j++) {
						JSONObject subFunciones = new JSONObject();

						subFunciones.put("text", module.getSubModulos().get(i)
								.getFunciones().get(j).getNbFuncion());
						subFunciones.put("nbFunction", module.getSubModulos()
								.get(i).getFunciones().get(j).getNbRuta());
						subFunciones.put("iconCls", module.getSubModulos().get(
								i).getFunciones().get(j).getNbIcon());
						subFunciones.put("nbClass", module.getSubModulos().get(
								i).getFunciones().get(j).getNbClass());
						arrayGuardaFunciones.put(subFunciones);
					}

					subModules.put("menu", arrayGuardaFunciones);
					arrayGuardaSubModulo.put(subModules);

				}
				arrayGuardaModulo.put(module.getNbModulo());

				// arrayGuardaModulo.put(new JSONObject().put("iconCls",
				// "silk-book"));

				arrayGuardaModulo.put(arrayGuardaSubModulo);
				array.put(arrayGuardaModulo);
			}
			object.put("success", "true");
			object.put("data", array);

			response.setContentType("text/html; charset=UTF-8");
			out.println(object.toString());
			return null;
		} catch (Exception e) {
			ActionMessages messages = new ActionMessages();
			ActionMessage msg = new ActionMessage("agv.adm.sec.incorrecto");
			messages.add("message", msg);
			saveMessages(request, messages);
			return mapping.findForward("login");
		}
	}

	/**
	 * Method execute
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward primerInicio(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		LoginForm loginForm = (LoginForm) form;
		try {
			if (loginForm.getCdAcceso().equals("")
					|| loginForm.getPwContra().equals("")) {
				ActionMessages messages = new ActionMessages();
				ActionMessage msg = new ActionMessage(
						"agv.adm.sec.campoRequerido");
				messages.add("message", msg);
				saveMessages(request, messages);
				return mapping.findForward("login");
			}

			Usuario usuario = (Usuario) request.getSession().getAttribute(
					"usuarioObj");
			securityService.validaPrimerAcceso(loginForm.getCdAcceso(),
					loginForm.getPwContra(), usuario.getIdUsuario());

		} catch (SecurityException e) {
			ActionMessages messages = new ActionMessages();
			ActionMessage msg = new ActionMessage(
					"agv.adm.sec.cdacceso.incorrecto");
			messages.add("message", msg);
			saveMessages(request, messages);
			return mapping.findForward("login");
		}
		return mapping.findForward("inicio");
	}

	public void setSecurityService(ISecurityService securityService) {
		this.securityService = securityService;
	}
}